package com.base.pig.util;



import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * @ProjectName yzgw_app
 * @Package com.example.yzgw.utils
 * @ClassName AesUtils
 * @Description 密码AES加密工具类
 * @Company LAB
 * @Author yanyajun
 * @Date 2020/4/3 10:29
 * @UpdateUser
 * @UpdateDate
 * @UpdateRemark
 * @Version 1.0.0
 */
@Slf4j
@Service
public class AesUtils {

    private static final String KEY_ALGORITHM = "AES";
    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();
    //TODO 密文使用配置文件
    private static final String key = "thanks,pig4cloud";

    public String decryptAES(String data) {
        AES aes = new AES(Mode.CBC, Padding.NoPadding,
                new SecretKeySpec(key.getBytes(), KEY_ALGORITHM),
                new IvParameterSpec(key.getBytes()));
        byte[] result = aes.decrypt(Base64.decode(data.getBytes(StandardCharsets.UTF_8)));
        return new String(result, StandardCharsets.UTF_8);
    }

    public String encryptAES(String data) {
        AES aes = new AES(Mode.CBC, Padding.ZeroPadding,
                new SecretKeySpec(key.getBytes(), KEY_ALGORITHM),
                new IvParameterSpec(key.getBytes()));
        return aes.encryptBase64(data);
    }
}

